/**
 * Created by zhanglihe on 15/11/19.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'dialog',
    'model',
    'datepicker'
], function ($, common, ready, Collection, template, dialog, Model, datepicker) {
    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.fetch();
            this.event();
        },

        fetch: function () {
            var _this = this;
            this.collection = new Collection({
                url: _global.url.api + 'user/withdraws',
                condition: {limit: 30, offset: 0},
                model: {
                    event: {
                        '.wx-agree:click': 'wxAgree',
                        '.alipay-agree:click': 'alipayAgree',
                        '.reject:click': 'reject'
                    },
                    wxAgree: function (e) {
                        e.preventDefault();
                        var _this_item = this;
                        dialog({
                            content: '确定要同意<br />[' + _this_item.data.user_name + ']<br />提现<br />' + _this_item.data.amount + '?',
                            modal: true,
                            ok: function () {
                                if (!new Model({
                                        url: _global.url.api + 'user/amount',
                                        data: {'act': 'agree', 'id': _this_item.data.id}
                                    }).put()) {
                                    return false;
                                }
                                _this.collection.fetch();
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    },
                    alipayAgree: function (e) {
                        setTimeout(function () {
                            _this.collection.reload();
                        }, 4000);
                    },
                    reject: function (e) {
                        e.preventDefault();
                        var _this_item = this;
                        dialog({
                            title: '拒绝提现',
                            width: 600,
                            content: template('data-item-reject', _this_item.data),
                            modal: true,
                            ok: function () {
                                if (!new Model({
                                        url: _global.url.api + 'user/amount',
                                        data: {
                                            'act': 'reject',
                                            'id': _this_item.data.id,
                                            'intro': $('[name=intro]').val()
                                        }
                                    }).put()) {
                                    return false;
                                }
                                _this.collection.fetch();
                            }, cancel: function () {
                            }
                        }).show();
                    }
                },
                callback: function () {
                    loaded();
                    _this.teller_arr = [];
                    var data = _this.collection.result.data;
                    for (var i = 0; i < data.length; i++) {
                        var _key = data[i].id;
                        _this.teller_arr[_key] = data[i];
                    }
                    console.log(_this.teller_arr);
                    $('.pagination').append('<li><a href="javascript:">记录总金额：￥' + _this.collection.result._amount + '</a></li>');
                    if (_this.collection.condition.method_type == 1) {
                        $('#agree,#wx-agree,.J_CheckItem').show();
                        $('#alipay-agree').hide();
                    }
                    else if (_this.collection.condition.method_type == 2) {
                        $('#agree,#alipay-agree,.J_CheckItem').show();
                        $('#wx-agree').hide();
                    }
                }
            });
            this.collection.fetch();
        },

        event: function () {
            var _this = this;
            var click_search = function (fun) {
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.condition.start_time = $('input[name="begintime"]').val();
                _this.collection.condition.end_time = $('input[name="endtime"]').val();
                _this.collection.condition.type = $("#type").val();
                _this.collection.callback = function () {
                    if (fun && fun == 'toExcel') {
                        toExcel();
                        _this.collection.callback = function () {
                        }
                    }
                }
                _this.collection.reload();
            };
//to excel
            var href;
            var toExcelWindow;
            $(".btn-excel").on("click", function (e) {
                e.preventDefault();
                href = $(this).attr('href');
                toExcelWindow = dialog({
                    content: '请稍等 ,正在导出...',
                    width: 200,
                    modal: true
                }).show();
                click_search('toExcel');
            });

            var toExcel = function () {
                toExcelWindow.close();
                console.log(_this.collection.result._count);
                var limit = 1000;
                var params = '';
                var data = _this.collection.condition;
                var total = _this.collection.result._count;

                if (total < 1) {
                    alert('没有需要导出的列表');
                    return false;
                }

                for (var i in data) {
                    if (i == 'limit' || i == 'offset') continue;
                    params = params + '&' + i + '=' + encodeURIComponent(data[i]);
                }
                href = (href.indexOf('?') === -1) ? href + '?' : href;
                href = href + params + '&limit=' + limit + '&offset=';

                if (total > limit) {
                    var showData = {};
                    showData.pages = Math.ceil(total / limit);
                    showData.total = total;
                    showData.limit = limit;
                    showData.href = href;
                    dialog({
                        title: '导出列表Excel文件',
                        content: template('to-excel-tpl', showData),
                        width: 600,
                        heigth: 500,
                        modal: true,
                        ok: function () {
                        },
                        cancel: function () {
                        }
                    }).show();
                } else {
                    window.location.href = href;
                }
            }

            $('.long_date').on('click', function () {
                WdatePicker({
                    el: this.id,
                    dateFmt: 'yyyy-MM-dd'
                });
            });
            /**
             * 按状态查询
             */
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.status = $(e.target).attr('rel');
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });
            $('#btn-method-type').find('a').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.method_type = $(e.target).attr('rel');
                if (_this.collection.condition.method_type == 2) {
                    _this.collection.condition.limit = 20;
                } else {
                    _this.collection.condition.limit = 30;
                }
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });

            /**
             * 搜索事件
             */
            $('#btn-search').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.condition.start_time = $('input[name="begintime"]').val();
                _this.collection.condition.end_time = $('input[name="endtime"]').val();
                _this.collection.condition.type = $("#type").val();
                _this.collection.reload();
            });
            $('#alipay-agree').on('click', function (e) {
                e.preventDefault();
                if ($('.J_CheckItem:checked').size() == 0) {
                    Alert({msg: '请先选择支付宝提现项目', type: 'error'});
                    return false;
                }
                var ids = '';
                $('.J_CheckItem:checked').each(function () {
                    var idTmp = $(this).val();
                    if (ids) {
                        ids = ids + ',' + idTmp;
                    } else {
                        ids = idTmp;
                    }
                });
                var url = '/admin/amount/user_withdraws_alipay?ids=' + ids;
                window.open(url);
                console.log(url);
                setTimeout(function () {
                    _this.collection.reload();
                }, 4000);
            });
            var _isopt;
            $('#wx-agree').on('click', function (e) {
                e.preventDefault();
                var _total = $('.J_CheckItem:checked').size();
                if (_total == 0) {
                    Alert({msg: '请先选择微信提现项目', type: 'error'});
                    return false;
                }
                _isopt = true;

                var teller_arr = _this.teller_arr;

                var _height = 80 + _total * 18;
                if (_height > 500)  _height = 500;

                var dialog_obj = dialog({
                    id: 'batch_agree_id',
                    title: '批量同意提现：',
                    content: '批量同意提现启动中...............',
                    width: 680,
                    height: _height,
                    modal: true,
                    cancelValue: '关闭|中止',
                    cancel: function () {
                        _isopt = false;
                    }
                });
                dialog_obj.show();

                //增加执行队列
                var opt_id_arr = [];
                $('.J_CheckItem:checked').each(function () {
                    opt_id_arr.push($(this).val());
                });

                var opt_i = 0;
                var old_opt_i = -1;
                var err_arr = [];

                //处理
                var int = self.setInterval(function () {
                    if (!_isopt) {
                        alert('已经中止操作');
                        dialog_obj.close();
                        int = window.clearInterval(int);
                        _this.collection.fetch();
                        return false;
                    }
                    if (opt_i >= _total) {
                        int = window.clearInterval(int);
                        _this.collection.fetch();

                        dialog_obj.title('全部处理完毕');
                        var errlength = err_arr.length;
                        if (errlength > 0) {
                            var _content = '处理总数：' + _total + '，其中成功：' + (_total - errlength) + '，失败：' + errlength + '<hr />';
                            for (i = 0; i < errlength; i++) {
                                _content += err_arr[i] + '<br />';
                            }
                            dialog_obj.content(_content);
                        }
                        return true;
                    }
                    if (old_opt_i > -1 && old_opt_i == opt_i) {
                        //中途错误，将继续处理
                        /*int=window.clearInterval(int);
                         _this.collection.fetch();*/
                        return false;
                    }
                    old_opt_i = opt_i;
                    var _id = opt_id_arr[opt_i];
                    var item = teller_arr[_id];
                    var _title = '当前操作（提现ID：' + item.id + '，提现人：' + item.account_name + '，提现金额：' + item.amount;
                    var _content = '需要处理：' + _total + ',已经处理：' + (opt_i + 1) + '<br /><br />';


                    dialog_obj.title(_title);

                    dialog_obj.content(_content);


                    if (new Model({
                            url: _global.url.api + 'user/amount',
                            data: {'act': 'agree', 'id': item.id}
                        }).put()) {
                        dialog_obj.content(_content + '当前操作:处理成功');
                    } else {
                        dialog_obj.content(_content + '当前操作:处理失败');
                        var err = '提现ID：' + item.id + ',提现人：' + item.account_name + '，提现金额：' + item.amount + "(处理失败)";
                        err_arr.push(err);
                    }
                    opt_i++;
                }, 100);
            });
            $('body').on('click', '.J_CheckItem, .chackall', function () {
                setTimeout(function () {
                    var teller_arr = _this.teller_arr;
                    console.log('item:start');
                    var i = 0;
                    var amount = 0.00;
                    $('.J_CheckItem:checked').each(function () {
                        var idTmp = $(this).val();
                        var item = teller_arr[idTmp];
                        i++;
                        var amountTmp = new Number(item.amount);
                        amountTmp = parseFloat(amountTmp.toFixed(2));
                        amount += amountTmp;
                        console.log(i + ',' + item.amount);
                    });
                    $('#show_amount_info').html(i > 0 ? '当前选择' + i + '条，合计' + parseFloat(amount.toFixed(2)) + '元' : '');
                    console.log('item:end');
                }, 500);
            });

        }
    };

    new index();

});